package main

import (
	"context"
	"github.com/redis/go-redis/extra/redisotel/v9"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/jaeger"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	"go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
)

const (
	traceName = "mxshop-otel"
)

var tp *trace.TracerProvider

func tracerProvider() error {
	url := "http://127.0.0.1:14268/api/traces" //这个是jeager对应的地址
	exporter, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))
	if err != nil {
		panic(err)
	}

	tp = trace.NewTracerProvider(
		trace.WithBatcher(exporter),
		trace.WithResource(resource.NewWithAttributes(
			semconv.SchemaURL,
			//设置trace的名称，不设置默认显示文件名
			semconv.ServiceNameKey.String("mxshop-redis"),
		)),
	)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
	return nil
}
func main() {

	_ = tracerProvider()
	client := redis.NewClient(&redis.Options{
		Addr: "127.0.0.1:6379",
	})

	if err := redisotel.InstrumentTracing(client); err != nil {
		panic(err)
	}

	tracer := otel.Tracer(traceName)
	spanCtx, span := tracer.Start(context.Background(), "redis")
	client.Set(spanCtx, "name", "ye", 0)
	span.End()
	tp.Shutdown(context.Background())

}
